<template>
  <div class="login-box">
    <img src=http://java-admin.likeadmin.cn/adminapi/static/login_image.png>
    <div class="login-form">
      <div class="login-form-title">likeadmin开源</div>

      <el-form ref="formRef" style="width: 100%" :model="formData" :rules="rules">

        <el-form-item prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号">
            <template #prepend>
              <div class="iconfont icon-zhanghaodenglu"></div>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" type="password">
            <template #prepend>
              <div class="iconfont icon-mima"></div>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="checkPass">
          <el-checkbox v-model="formData.checkPass" label="记住密码" size="large"/>
        </el-form-item>

        <el-form-item>
          <el-button @click="submitForm(formRef)" type="primary" style="width: 100%">登 录</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import MD5 from 'js-md5'
import {postLogin} from "@/api/request.js";
import {setToken} from "@/utils";

const $router = useRouter()
const $route = useRoute()

const formRef = ref()

const formData = reactive({
  username: '',
  password: '',
  checkPass: false
})

const validate = (rule, value, callback) => {
  if (rule.fullField === 'username') {
    if (!value) {
      callback(new Error('用户名不能为空'));
    } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
      callback(new Error('用户名只能包含字母和数字'));
    } else {
      callback();
    }
  }
  if (rule.fullField === 'password') {
    if (!value) {
      callback(new Error('请输入密码'));
    } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
      callback(new Error('密码只能包含字母和数字'));
    } else {
      callback();
    }
  }
};
const rules = reactive({
  username: [{validator: validate, trigger: 'blur'}],
  password: [{validator: validate, trigger: 'blur'}],
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    try {
      const {data} = await postLogin({
        username: formData.username,
        password: MD5(formData.password)
      })
      setToken({
        username: formData.username,
        token: data.access_token,
        checkPass: formData.checkPass
      })
      // $router.push(($route.query.redirect as string) || '/')
      $router.push('/home')
    } catch (error) {
      console.error('登录失败:', error)
    }
  })
}
</script>


<style scoped>

</style>